package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.ContractRelation;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerMainOriginal;
import com.isunland.managesystem.entity.CustomerNeed;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.entity.ProjectLedger;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineViewNew;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  项目台账详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/5/15 14:05
 */
public class ProjectLedgerDetailFragment extends BaseFragment implements View.OnClickListener {

  @BindView(R.id.sl_projectKindName) SingleLineViewNew slProjectKindName;
  @BindView(R.id.sl_projectName) SingleLineViewNew slProjectName;
  @BindView(R.id.sl_projectSignDate) SingleLineViewNew slProjectSignDate;
  @BindView(R.id.sl_ifMainRec) SingleLineViewNew slIfMainRec;
  @BindView(R.id.sl_mainproject) SingleLineViewNew slMainproject;
  @BindView(R.id.sl_pmDeptName) SingleLineViewNew slPmDeptName;
  @BindView(R.id.sl_pmName) SingleLineViewNew slPmName;
  @BindView(R.id.sl_requireDate) SingleLineViewNew slRequireDate;
  @BindView(R.id.sl_pmappName) SingleLineViewNew slPmappName;
  @BindView(R.id.sl_pmappDeptName) SingleLineViewNew slPmappDeptName;
  @BindView(R.id.sl_tenderOffer) SingleLineViewNew slTenderOffer;
  @BindView(R.id.sl_principalNames) SingleLineViewNew slPrincipalNames;
  @BindView(R.id.cb_ifAcceptance) CheckBox cbIfAcceptance;
  @BindView(R.id.sl_finishDate) SingleLineViewNew slFinishDate;
  @BindView(R.id.sl_projectPlanfee) SingleLineViewNew slProjectPlanfee;
  @BindView(R.id.cb_ifClose) CheckBox cbIfClose;
  @BindView(R.id.sl_closeSetdate) SingleLineViewNew slCloseSetdate;
  @BindView(R.id.sl_projectRealfee) SingleLineViewNew slProjectRealfee;
  @BindView(R.id.sl_partaName) SingleLineViewNew slPartaName;
  @BindView(R.id.sl_partaLinkName) SingleLineViewNew slPartaLinkName;
  @BindView(R.id.sl_partaLinkPhone) SingleLineViewNew slPartaLinkPhone;
  @BindView(R.id.sl_partaEmail) SingleLineViewNew slPartaEmail;
  @BindView(R.id.sl_partbName) SingleLineViewNew slPartbName;
  @BindView(R.id.sl_partbLinkName) SingleLineViewNew slPartbLinkName;
  @BindView(R.id.sl_partbLinkPhone) SingleLineViewNew slPartbLinkPhone;
  @BindView(R.id.sl_partbEmail) SingleLineViewNew slPartbEmail;
  @BindView(R.id.ll_partab) LinearLayout llPartab;
  @BindView(R.id.sl_dataStatusName) SingleLineViewNew slDataStatusName;
  @BindView(R.id.sl_regStaffName) SingleLineViewNew slRegStaffName;
  @BindView(R.id.sl_regDate) SingleLineViewNew slRegDate;
  @BindView(R.id.sl_needProduct) SingleLineViewNew slNeedProduct;
  @BindView(R.id.sl_projectCode) SingleLineViewNew slProjectCode;
  @BindView(R.id.sl_relContractName) SingleLineViewNew slContractName;

  private ProjectLedger mContent;
  private CurrentUser mUser;
  private String mId;

  private final int SAVE_RUN = 0;
  private final int OTHER = 1;

  private int mMenuType;
  private final int ADD = 0;
  private final int NEW = 1;
  private final int SUBMIT = 2;
  private final int CHECK_PASS = 3;

  public static final int REQUEST_DELETE = 4;
  public static final int REQUEST_SUBMIT = 5;
  private final int REQUEST_SIGNDATE = 6;
  private final int REQUEST_REQUIREDATE = 7;
  private final int REQUEST_FINISHDATE = 8;
  private final int REQUEST_CLOSESETDATE = 9;
  private final int REQUEST_PRINCIPAL = 10;
  private final int REQUEST_PMAPP = 11;
  private final int REQUEST_PMNAME = 12;
  private final int REQUEST_NEEDPRODUST = 13;
  private final int RREQUEST_PROJECT_KIND = 14;
  private final int REQUEST_IFMIAN = 15;
  private final int REQUEST_ACUSTOMER = 16;
  private final int REQUEST_BCUSTOMER = 17;
  private final int REQUEST_MAIN_PROJECT = 18;
  private final int REQUEST_BDEPT = 19;
  private final int REQUEST_ADEPT = 20;
  private final int REQUEST_CJDEPT = 21;
  private final int REQUEST_PARTALINK = 22;
  private final int REQUEST_PARTBLINK = 23;

  private final String WT = "WWXM";//委托类
  private final String CJ = "CJXM";//承接类
  private final String NB = "NBXM";//内部类

  private String principalCodes;
  private String pmappId;
  private String pmId;
  private String needProductId;
  private String projectFlag;
  private String pmappDeptCode;
  private String ifMainRec;
  private String mDataStatus;
  private String mainprojectId;
  private String pmDeptCode;
  private String partaId;
  private String partbDeptId;
  private String partbLinkId;
  private String partaLinkId;
  private String projectKindCode;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mContent =
        (ProjectLedger) getArguments().getSerializable(ProjectLedgerPagerActivity.EXTRA_CONTENT);
    mUser = CurrentUser.newInstance(getActivity());
    if (mContent == null) {
      //添加
      setTitleCustom(R.string.projectLedgerReg);
      mId = UUID.randomUUID().toString();
      principalCodes = "";
      needProductId = "";
      pmappId = "";
      pmId = "";
      projectFlag = "";
      pmappDeptCode = "";
      ifMainRec = "main";
      mainprojectId = "";
      pmDeptCode = "";
      partaId = "";
      partbDeptId = "";
      partaLinkId = "";
      partbLinkId = "";
      projectKindCode = "";
      mDataStatus = DataStatus.NEW;
      mMenuType = ADD;
    } else {
      mId = mContent.getId();
      projectKindCode = mContent.getProjectKindCode();
      principalCodes = mContent.getPrincipalCodes();
      needProductId = mContent.getNeedProductId();
      pmappId = mContent.getPmappId();
      pmId = mContent.getPmId();
      projectFlag = mContent.getProjectFlag();
      pmappDeptCode = mContent.getPmappDeptCode();
      ifMainRec = mContent.getIfMainRec();
      mainprojectId = mContent.getMainprojectId();
      pmDeptCode = mContent.getPmDeptCode();
      partaId = mContent.getPartaId();
      partbDeptId = mContent.getPartbDeptId();
      partaLinkId = mContent.getPartaLinkId();
      partbLinkId = mContent.getPartbLinkId();
      mDataStatus = mContent.getDataStatus();
      if (mDataStatus.equalsIgnoreCase(DataStatus.NEW) || mDataStatus.equalsIgnoreCase(
          DataStatus.NEWBACK)) {
        mMenuType = NEW;
      } else if (mDataStatus.equalsIgnoreCase(DataStatus.SUBMIT)) {
        mMenuType = SUBMIT;
      } else {
        mMenuType = CHECK_PASS;
      }
    }
  }

  @Override public void onStart() {
    super.onStart();
    //获取关联合同
    volleyPostContract();
  }

  private void volleyPostContract() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RELATE_CONTRACT_LIST);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("isPaging", "1");
    params.put("dataType", "project");
    params.put("relationType", "project");
    params.put("orderField", "reg_date");
    params.put("orderSeq", "desc");
    params.put("projectId", mId);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {

        BaseOriginal<ContractRelation> original =
            new Gson().fromJson(json, new TypeToken<BaseOriginal<ContractRelation>>() {
            }.getType());
        List<ContractRelation> rows = original.getRows();
        ArrayList<ContractRelation> mList = new ArrayList<>();
        if (Base.SUCCESS == original.getResult()) {
          mList.addAll(rows);
          StringBuilder bufferNames = new StringBuilder();
          for (int i = 0; i < mList.size(); i++) {
            ContractRelation item0 = mList.get(i);
            if (item0 == null) continue;
            String name = item0.getContractName();
            if (bufferNames.length() > 0) {
              bufferNames.append(",").append(name);
            } else {
              bufferNames.append(name);
            }
          }
          slContractName.setTextContent(bufferNames.toString());
        }
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (mMenuType) {
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        break;
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      case SUBMIT:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      case CHECK_PASS:
        break;
      default:
        break;
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();

        return true;
      case R.id.menu_item_save:
        //只能修改自己登记的记录
        if (mContent == null || mUser.getJobNumber().equalsIgnoreCase(mContent.getRegStaffId())) {
          if (isCorrectInput()) {
            volleyPostSave(OTHER);
          }
        } else {
          ToastUtil.show(R.string.onlyCreater);
        }

        return true;
      case R.id.menu_item_submit:
        //保存并启动流程
        if (mContent == null || mUser.getJobNumber().equalsIgnoreCase(mContent.getRegStaffId())) {
          if (isCorrectInput()) {
            showDialog(BaseConfirmDialogFragment.newInstance(R.string.start_up_hint),
                REQUEST_SUBMIT);
          }
        } else {
          ToastUtil.show(R.string.onlyCreater);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        if (mUser.getJobNumber().equalsIgnoreCase(mContent.getRegStaffId())) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        } else {
          ToastUtil.show(R.string.onlyCreater);
        }
        return true;
      // 终止流程
      case R.id.menu_item_stop:
        if (mUser.getJobNumber().equalsIgnoreCase(mContent.getRegStaffId())) {
          volleyPostStop(OTHER);
        } else {
          ToastUtil.show(R.string.onlyCreater);
        }
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_project_ledger_detail, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    slPrincipalNames.getViewContent().setSingleLine(false);
    slMainproject.getViewContent().setSingleLine(false);
    slPartaName.getViewContent().setSingleLine(false);
    slPartbName.getViewContent().setSingleLine(false);
    if (mContent != null) {
      //详情
      slProjectKindName.setTextContent(mContent.getProjectKindName());
      slProjectName.setTextContent(mContent.getProjectName());
      slProjectCode.setTextContent(mContent.getProjectKindCode());
      slProjectSignDate.setTextContent(mContent.getProjectSignDate());
      if ("main".equalsIgnoreCase(mContent.getIfMainRec())) {
        slIfMainRec.setTextContent("主项目");
        slMainproject.setVisibility(View.GONE);
      }
      if ("sub".equalsIgnoreCase(mContent.getIfMainRec())) {
        slIfMainRec.setTextContent("子项目");
        slMainproject.setVisibility(View.VISIBLE);
        slMainproject.setTextContent(mContent.getRemark());//主项目名
      }
      slPmDeptName.setTextContent(mContent.getPmDeptName());
      slPmName.setTextContent(mContent.getPmName());
      slRequireDate.setTextContent(mContent.getRequireDate());
      slPmappName.setTextContent(mContent.getPmappName());
      slPmappDeptName.setTextContent(mContent.getPmappDeptName());
      slTenderOffer.setTextContent(mContent.getTenderOffer());//所属招标
      slPrincipalNames.setTextContent(mContent.getPrincipalNames());
      slNeedProduct.setTextContent(mContent.getNeedProductDesc());
      if ("T".equalsIgnoreCase(mContent.getIfAcceptance())) {
        cbIfAcceptance.setChecked(true);
        slFinishDate.getViewContent().setEnabled(true);
      } else {
        cbIfAcceptance.setChecked(false);
        slFinishDate.getViewContent().setEnabled(false);
      }

      slFinishDate.setTextContent(mContent.getFinishDate());
      slProjectPlanfee.setTextContent(mContent.getProjectPlanfee());
      if ("T".equalsIgnoreCase(mContent.getIfClose())) {
        cbIfClose.setChecked(true);
        slCloseSetdate.getViewContent().setEnabled(true);
      } else {
        cbIfClose.setChecked(false);
        slCloseSetdate.getViewContent().setEnabled(false);
      }
      slCloseSetdate.setTextContent(mContent.getCloseSetdate());
      slProjectRealfee.setTextContent(mContent.getProjectRealfee());
      slPartaName.setTextContent(mContent.getPartaName());
      slPartaLinkName.setTextContent(mContent.getPartaLinkName());
      slPartaLinkPhone.setTextContent(mContent.getPartaLinkPhone());
      slPartaEmail.setTextContent(mContent.getPartaEmail());
      slPartbName.setTextContent(mContent.getPartbDeptName());
      slPartbLinkName.setTextContent(mContent.getPartbLinkName());
      slPartbLinkPhone.setTextContent(mContent.getPartbLinkPhone());
      slPartbEmail.setTextContent(mContent.getPartbEmail());

      //项目类别为内部类时,隐藏甲方乙方
      if (NB.equalsIgnoreCase(projectFlag)) {
        llPartab.setVisibility(View.GONE);
      } else if (CJ.equalsIgnoreCase(projectFlag)) {
        //承接类: 乙方为本公司
        llPartab.setVisibility(View.VISIBLE);
        slPartbLinkName.setType(SingleLineViewNew.NEXT);
      } else if (WT.equalsIgnoreCase(projectFlag)) {
        //委托类: 甲方为本公司
        llPartab.setVisibility(View.VISIBLE);
        slPartaLinkName.setType(SingleLineViewNew.NEXT);
      }

      MyUtils.switchShadowStutus(getActivity(), slDataStatusName.getViewContent(),
          mContent.getDataStatus());
      slRegStaffName.setTextContent(mContent.getRegStaffName());
      slRegDate.setTextContent(mContent.getRegDate());
    } else {
      //添加
      slIfMainRec.setTextContent("主项目");
      slMainproject.setVisibility(View.GONE);
      slProjectPlanfee.setTextContent("0.00");
      slProjectRealfee.setTextContent("0.00");
      slDataStatusName.setTextContent(getResources().getString(R.string.draft));
      slRegStaffName.setTextContent(mUser.getRealName());
      slRegDate.setTextContent(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
      slFinishDate.getViewContent().setEnabled(false);
      slCloseSetdate.getViewContent().setEnabled(false);
    }

    cbIfAcceptance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
        if (isCheck) {
          slFinishDate.getViewContent().setEnabled(true);
        } else {
          slFinishDate.getViewContent().setEnabled(false);
          slFinishDate.setTextContent("");
        }
      }
    });
    cbIfClose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
        if (isCheck) {
          slCloseSetdate.getViewContent().setEnabled(true);
        } else {
          slCloseSetdate.getViewContent().setEnabled(false);
          slCloseSetdate.setTextContent("");
        }
      }
    });
    slProjectKindName.setOnClickContentListener(this);
    slProjectSignDate.setOnClickContentListener(this);
    slIfMainRec.setOnClickContentListener(this);
    slMainproject.setOnClickContentListener(this);
    slPmDeptName.setOnClickContentListener(this);
    slPmName.setOnClickContentListener(this);
    slRequireDate.setOnClickContentListener(this);
    slPmappName.setOnClickContentListener(this);
    slPrincipalNames.setOnClickContentListener(this);
    slNeedProduct.setOnClickContentListener(this);
    slContractName.setOnClickContentListener(this);
    slFinishDate.setOnClickContentListener(this);
    slCloseSetdate.setOnClickContentListener(this);
    slPartaName.setOnClickContentListener(this);
    slPartbName.setOnClickContentListener(this);
    slPartaName.setOnClickContentListener(this);
    slPartaLinkName.setOnClickContentListener(this);
    slPartbLinkName.setOnClickContentListener(this);
    if (DataStatus.SUBMIT.equalsIgnoreCase(mDataStatus) || DataStatus.PUBLIS.equalsIgnoreCase(
        mDataStatus)) {
      //详情
      slProjectKindName.getViewContent().setEnabled(false);
      slProjectName.getViewContent().setEnabled(false);
      slProjectCode.getViewContent().setEnabled(false);
      slProjectSignDate.getViewContent().setEnabled(false);
      slIfMainRec.getViewContent().setEnabled(false);
      slMainproject.getViewContent().setEnabled(false);
      slPmDeptName.getViewContent().setEnabled(false);
      slPmName.getViewContent().setEnabled(false);
      slRequireDate.getViewContent().setEnabled(false);
      slPmappName.getViewContent().setEnabled(false);
      slPmappDeptName.getViewContent().setEnabled(false);
      slTenderOffer.getViewContent().setEnabled(false);//所属招标
      slPrincipalNames.getViewContent().setEnabled(false);
      slNeedProduct.getViewContent().setEnabled(false);
      slContractName.getViewContent().setEnabled(false);
      cbIfAcceptance.setEnabled(false);
      slFinishDate.getViewContent().setEnabled(false);
      slProjectPlanfee.getViewContent().setEnabled(false);
      cbIfClose.setEnabled(false);
      slCloseSetdate.getViewContent().setEnabled(false);
      slProjectRealfee.getViewContent().setEnabled(false);
      slPartaName.getViewContent().setEnabled(false);
      slPartaLinkName.getViewContent().setEnabled(false);
      slPartaLinkPhone.getViewContent().setEnabled(false);
      slPartaEmail.getViewContent().setEnabled(false);
      slPartbName.getViewContent().setEnabled(false);
      slPartbLinkName.getViewContent().setEnabled(false);
      slPartbLinkPhone.getViewContent().setEnabled(false);
      slPartbEmail.getViewContent().setEnabled(false);
    }
  }

  //保存
  private void volleyPostSave(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_LEDGER_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("ifBegin", "F");//是否期初 固定值F
    params.put("id", mId);//项目id
    params.put("storeId", "");//储备项目ID
    params.put("dataStatus", mDataStatus);//数据状态
    params.put("projectKindCode", projectKindCode);//项目类别
    params.put("projectKindName", slProjectKindName.getTextContent());//项目类别名称
    params.put("projectFlag", projectFlag);// 项目标识
    params.put("projectName", slProjectName.getTextContent());//项目名称
    params.put("projectCode", slProjectCode.getTextContent());//项目编码
    params.put("projectSignDate", slProjectSignDate.getTextContent());//签订日期
    params.put("ifMainRec", ifMainRec); //主/子项目 默认是main
    params.put("remark", slMainproject.getTextContent());//主项目名称
    params.put("mainprojectId", mainprojectId);// 主项目id
    params.put("pmDeptCode", pmDeptCode);//承建项目组编码
    params.put("pmDeptName", slPmDeptName.getTextContent());//承建项目组
    params.put("pmName", slPmName.getTextContent());//项目经理
    params.put("pmId", pmId);//项目经理jobno
    params.put("requireDate", slRequireDate.getTextContent());//要求完成时间
    params.put("pmappName", slPmappName.getTextContent());//项目经理任命人
    params.put("pmappId", pmappId);//项目经理任命人jobno
    params.put("pmappDeptCode", pmappDeptCode);//任命人部门编码
    params.put("pmappDeptName", slPmappDeptName.getTextContent());//任命人部门
    params.put("tenderOffer", slTenderOffer.getTextContent());//所属招标
    params.put("principalCodes", principalCodes);//参与人jobno
    params.put("principalNames", slPrincipalNames.getTextContent());//参与人
    params.put("needProductDesc", slNeedProduct.getTextContent());//客户需求描述
    params.put("needProductId", needProductId);//客户需求id
    //if (cbIfAcceptance.isChecked()) {
    //  params.put("ifAcceptance", "T");//是否验收 默认F
    //} else {
    //  params.put("ifAcceptance", "F");//是否验收 默认F
    //}
    //params.put("finishDate", slFinishDate.getTextContent());//实际完成时间
    params.put("projectPlanfee", slProjectPlanfee.getTextContent());//计划费用
    if (cbIfClose.isChecked()) {
      params.put("ifClose", "T"); //是否关闭 默认F
    } else {
      params.put("ifClose", "F");//是否验收 默认F
    }
    params.put("closeSetdate", slCloseSetdate.getTextContent());//关闭时间
    params.put("closeSetmanId", mUser.getJobNumber());//关闭人
    params.put("projectRealfee", slProjectRealfee.getTextContent());//实际费用
    //甲方乙方
    params.put("partaId", partaId);//甲方单位名称
    params.put("partaName", slPartaName.getTextContent());//甲方单位
    params.put("partaLinkName", slPartaLinkName.getTextContent());//甲方联系人
    params.put("partaLinkId", partaLinkId);//甲方联系jobno
    params.put("partaEmail", slPartaEmail.getTextContent());//甲方邮箱
    params.put("partaLinkPhone", slPartaLinkPhone.getTextContent());//甲方电话
    params.put("partbDeptId", partbDeptId);//乙方单位
    params.put("partbDeptName", slPartbName.getTextContent());//乙方单位名称
    params.put("partbLinkName", slPartbLinkName.getTextContent());//乙方联系人
    params.put("partbLinkId", partbLinkId);//乙方联系jobno
    params.put("partbEmail", slPartbEmail.getTextContent());//乙方邮箱
    params.put("partbLinkPhone", slPartbLinkPhone.getTextContent());//乙方电话
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse(requestCode));
  }

  //删除
  private void volleyPostDel(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_LEDGER_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse(requestCode));
  }

  //终止
  private void volleyPostStop(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_LEDGER_STOP);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("dataStatus", DataStatus.NEWBACK);
    params.put("runId", mContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse(requestCode));
  }

  //启动
  private void volleyPostStart(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PROJECT_LEDGER_START);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("idList", "1");
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse(requestCode));
  }

  /* 必填项*/
  public boolean isCorrectInput() {
    if (TextUtils.isEmpty(slProjectKindName.getTextContent())
        || TextUtils.isEmpty(slProjectName.getTextContent())
        || TextUtils.isEmpty(slProjectCode.getTextContent())
        || TextUtils.isEmpty(slProjectSignDate.getTextContent())
        || TextUtils.isEmpty(slRequireDate.getTextContent())) {
      ToastUtil.show(R.string.complete_hint);
      return false;
    } else {
      return true;
    }
  }

  public VolleyResponse getResponse(final int requestCode) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            switch (requestCode) {
              case SAVE_RUN:
                volleyPostStart(OTHER);
                break;
              case OTHER:
                ToastUtil.show(successsMessage.getMessage());
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
                break;
              default:
                break;
            }
          } else {
            ToastUtil.show(successsMessage.getMessage());
          }
        } catch (Exception e) {
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  @Override public void onClick(View view) {
    if (!(view.getTag() instanceof Integer)) return;
    int id = (int) view.getTag();
    switch (id) {
      case R.id.sl_projectKindName:
        //项目类别
        getProjectKind();
        break;
      case R.id.sl_projectSignDate:
        //签订日期
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date()), REQUEST_SIGNDATE);
        break;
      case R.id.sl_ifMainRec:
        //主子项目
        showDialog(new IfMainDialogFrament(), REQUEST_IFMIAN);
        break;
      case R.id.sl_mainproject:
        //主项目
        Intent mainProject = new Intent(getActivity(), ProjectChooseListActivity.class);
        startActivityForResult(mainProject, REQUEST_MAIN_PROJECT);
        break;
      case R.id.sl_pmDeptName:
        //项目组
        getDeptKind();
        break;
      case R.id.sl_pmName:
        //项目经理
        choosePerson(REQUEST_PMNAME);
        break;
      case R.id.sl_requireDate:
        //要求完成时间
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date()), REQUEST_REQUIREDATE);
        break;
      case R.id.sl_pmappName:
        //经理任命人
        choosePerson(REQUEST_PMAPP);
        break;
      case R.id.sl_principalNames:
        //参与人
        Intent principalNames = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        principalNames.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        principalNames.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, principalCodes);
        startActivityForResult(principalNames, REQUEST_PRINCIPAL);
        break;
      case R.id.sl_needProduct:
        //客户需求
        Intent needProduct = new Intent(getActivity(), CustomerNeedProductActivity.class);
        startActivityForResult(needProduct, REQUEST_NEEDPRODUST);
        break;
      case R.id.sl_relContractName:
        //关联合同
        mBaseParams.setId(mId);//项目id
        int REQUEST_CONTRACT = 24;
        ContractRelateListActivity.newInstance(this, ContractRelateListActivity.class, mBaseParams,
            REQUEST_CONTRACT);
        break;
      case R.id.sl_finishDate:
        //实际完成时间
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date()), REQUEST_FINISHDATE);
        break;
      case R.id.sl_closeSetdate:
        //关闭时间
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date()), REQUEST_CLOSESETDATE);
        break;
      case R.id.sl_partaName:
        //甲方单位
        if (WT.equalsIgnoreCase(projectFlag)) {
          //委托类 : 本公司
          showDialog(AppObjectDialogFragment.newInstance(AppObjectDialogFragment.COMPANY),
              REQUEST_ADEPT);
        } else if (CJ.equalsIgnoreCase(projectFlag)) {
          //承接类: 客户
          Intent customer = new Intent(getActivity(), CustomerListChooseActivity.class);
          startActivityForResult(customer, REQUEST_ACUSTOMER);
        } else {
          ToastUtil.show("请先选择项目类别");
        }
        break;
      case R.id.sl_partbName:
        //乙方单位
        if (WT.equalsIgnoreCase(projectFlag)) {
          //委托类: 客户
          Intent customer = new Intent(getActivity(), CustomerListChooseActivity.class);
          startActivityForResult(customer, REQUEST_BCUSTOMER);
        } else if (CJ.equalsIgnoreCase(projectFlag)) {
          //承接类: 本公司
          showDialog(AppObjectDialogFragment.newInstance(AppObjectDialogFragment.COMPANY),
              REQUEST_BDEPT);
        } else {
          ToastUtil.show("请先选择项目类别");
        }
        break;
      case R.id.sl_partaLinkName:
        //甲方联系人
        if (WT.equalsIgnoreCase(projectFlag)) {
          //承接类: 本公司
          choosePerson(REQUEST_PARTALINK);
        }
        break;
      case R.id.sl_partbLinkName:
        //乙方联系人
        if (CJ.equalsIgnoreCase(projectFlag)) {
          //承接类: 本公司
          choosePerson(REQUEST_PARTBLINK);
        }
        break;
      default:
        break;
    }
  }

  private void choosePerson(int requestCode) {
    Intent person = new Intent(getActivity(), SearchPersonActivity.class);
    person.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
    startActivityForResult(person, requestCode);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_SUBMIT) {
      //保存并提交
      volleyPostSave(SAVE_RUN);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDel(OTHER);
    }
    if (requestCode == RREQUEST_PROJECT_KIND) {
      //项目类别
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      projectFlag = item.getExtParam2();
      projectKindCode = item.getExtParam();
      slProjectKindName.setTextContent(item.getName());
      //甲方乙方信息置为空
      clearPartab();

      if (CJ.equalsIgnoreCase(projectFlag)) {
        //承接类: 甲方为客户,乙方为本公司联系人员可选
        llPartab.setVisibility(View.VISIBLE);
        slPartaLinkName.setInputType(SingleLineViewNew.TEXT);
        //slPartbLinkName.setInputType(SingleLineViewNew.NEXT);
        slPartbLinkName.setType(SingleLineViewNew.NEXT);
      }
      if (NB.equalsIgnoreCase(projectFlag)) {
        //内部类: 隐藏甲方乙方
        llPartab.setVisibility(View.GONE);
      }
      if (WT.equalsIgnoreCase(projectFlag)) {
        //委托类: 甲方为本公司联系人员可选,乙方为客户
        llPartab.setVisibility(View.VISIBLE);
        slPartaLinkName.setType(SingleLineViewNew.NEXT);
        slPartbLinkName.setInputType(SingleLineViewNew.TEXT);
      }
      //获取项目编码
      volleyPostGetCode(projectFlag);
    }
    if (requestCode == REQUEST_SIGNDATE
        || requestCode == REQUEST_REQUIREDATE
        || requestCode == REQUEST_FINISHDATE
        || requestCode == REQUEST_CLOSESETDATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String datestr = MyDateUtil.format(date, MyDateUtil.TYPE_DATE);
      switch (requestCode) {
        case REQUEST_SIGNDATE:
          slProjectSignDate.setTextContent(datestr);
          break;
        case REQUEST_REQUIREDATE:
          slRequireDate.setTextContent(datestr);
          break;
        case REQUEST_FINISHDATE:
          slFinishDate.setTextContent(datestr);
          break;
        case REQUEST_CLOSESETDATE:
          slCloseSetdate.setTextContent(datestr);
          break;
        default:
          break;
      }
    }
    if (requestCode == REQUEST_IFMIAN) {
      CustomerDialog ifmian =
          (CustomerDialog) data.getSerializableExtra(IfMainDialogFrament.EXTRA_IFMAIN);
      ifMainRec = ifmian.getId();
      slIfMainRec.setTextContent(ifmian.getName());
      LogUtil.i("ifMainRec===" + ifMainRec);
      //选择主项目:主项目隐藏   选择子项目:  主项目显示
      if ("main".equalsIgnoreCase(ifMainRec)) {
        slMainproject.setVisibility(View.GONE);
      } else if ("sub".equalsIgnoreCase(ifMainRec)) {
        slMainproject.setVisibility(View.VISIBLE);
      }
    }
    if (requestCode == REQUEST_MAIN_PROJECT) {
      ProjectCollectOriginal.ProjectCollectContent objectContent =
          (ProjectCollectOriginal.ProjectCollectContent) data.getSerializableExtra(
              ProjectChooseListFragment.EXTRA_CONTENT);
      mainprojectId = objectContent.getId();
      String remark = objectContent.getProjectName();
      slMainproject.setTextContent(remark);
    }

    if (requestCode == REQUEST_PRINCIPAL) {
      principalCodes = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      String principalNames = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      slPrincipalNames.setTextContent(principalNames);
    }
    if (requestCode == REQUEST_CJDEPT) {
      //承接项目组
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      pmDeptCode = item.getId();//承建项目组 code
      String pmDeptName = item.getName();//项目组名
      slPmDeptName.setTextContent(pmDeptName);
    }
    if (requestCode == REQUEST_PMAPP
        || requestCode == REQUEST_PMNAME
        || requestCode == REQUEST_PARTALINK
        || requestCode == REQUEST_PARTBLINK) {
      CustomerDialog person =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      String personId = person.getId();//人员jobno
      String personName = person.getName();//人员name
      String deptCode = person.getMemberCode();//部门name
      String deptName = person.getDept();//部门code
      switch (requestCode) {
        case REQUEST_PMAPP:
          //经理任命人; 需要带回任命人部门
          pmappId = personId;
          pmappDeptCode = deptCode;
          slPmappName.setTextContent(personName);
          slPmappDeptName.setTextContent(deptName);
          break;
        case REQUEST_PMNAME:
          //项目经理
          pmId = personId;
          slPmName.setTextContent(personName);
          break;
        case REQUEST_PARTALINK:
          //甲方联系人
          partaLinkId = personId;
          slPartaLinkName.setTextContent(personName);
          break;
        case REQUEST_PARTBLINK:
          //乙方联系人
          partbLinkId = personId;
          slPartbLinkName.setTextContent(personName);
          break;
        default:
          break;
      }
    }
    if (requestCode == REQUEST_NEEDPRODUST) {
      CustomerNeed customerNeed =
          (CustomerNeed) data.getSerializableExtra(CustomerNeedProductFragment.EXTRA_VALUE);
      needProductId = customerNeed.getId();
      String needProductDesc = customerNeed.getNeedProductDesc();
      slNeedProduct.setTextContent(needProductDesc);
    }
    if (requestCode == REQUEST_ACUSTOMER) {
      //甲方客户
      CustomerMainOriginal.rCustomerMain customer =
          (CustomerMainOriginal.rCustomerMain) data.getSerializableExtra(
              CustomerListChooseFragment.EXTRA_CONTENT);
      partaId = customer.getId();
      String partaName = customer.getCustomerName();
      partaLinkId = customer.getCustomerName();
      String partaLinkName = customer.getContactManNames();
      String partaLinkPhone = customer.getContactNum();
      String partaEmail = customer.getLinkmanEmail();
      slPartaName.setTextContent(partaName);
      slPartaLinkName.setTextContent(partaLinkName);
      slPartaLinkPhone.setTextContent(partaLinkPhone);
      slPartaEmail.setTextContent(partaEmail);
    }
    if (requestCode == REQUEST_BCUSTOMER) {
      //乙方客户
      CustomerMainOriginal.rCustomerMain customer =
          (CustomerMainOriginal.rCustomerMain) data.getSerializableExtra(
              CustomerListChooseFragment.EXTRA_CONTENT);
      partbDeptId = customer.getId();
      String partbDeptName = customer.getCustomerName();
      partbLinkId = "";
      String partbLinkName = customer.getContactManNames();
      String partbLinkPhone = customer.getContactNum();
      String partbEmail = customer.getLinkmanEmail();
      slPartbName.setTextContent(partbDeptName);
      slPartbLinkName.setTextContent(partbLinkName);
      slPartbLinkPhone.setTextContent(partbLinkPhone);
      slPartbEmail.setTextContent(partbEmail);
    }
    if (requestCode == REQUEST_ADEPT) {
      //甲方: 本公司
      CustomerDialog dept =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      partaId = dept.getId();
      String partaName = dept.getName();
      slPartaName.setTextContent(partaName);
    }
    if (requestCode == REQUEST_BDEPT) {
      //乙方: 本公司
      CustomerDialog dept =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      partbDeptId = dept.getId();
      String partbDeptName = dept.getName();
      slPartbName.setTextContent(partbDeptName);
    }
  }

  private void clearPartab() {
    //甲方
    partaId = "";
    partaLinkId = "";
    slPartaName.setTextContent("");
    slPartaLinkName.setTextContent("");
    slPartaLinkPhone.setTextContent("");
    slPartaEmail.setTextContent("");
    //乙方
    partbDeptId = "";
    partbLinkId = "";
    slPartbName.setTextContent("");
    slPartbLinkName.setTextContent("");
    slPartbLinkPhone.setTextContent("");
    slPartbEmail.setTextContent("");
  }

  private void volleyPostGetCode(String flag) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PROJECT_CODE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", mUser.getMemberCode());
    params.put("projectFlag", flag);//项目类型标识
    params.put("type", "mobile");
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
        String successType = successsMessage.getResult();
        if (successType.equals("1")) {
          slProjectCode.setTextContent(successsMessage.getMessage());
        }
      }
    });
  }

  public static ProjectLedgerDetailFragment newInstance(ProjectLedger content) {
    Bundle args = new Bundle();
    args.putSerializable(ProjectLedgerPagerActivity.EXTRA_CONTENT, content);
    ProjectLedgerDetailFragment fragment = new ProjectLedgerDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  /** 获取项目类别 */
  public void getProjectKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("选择项目类型");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_PROJECT_TYPE_TREE);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dictFlag", "projectKindCode")
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, RREQUEST_PROJECT_KIND);
  }

  /** 获取承接项目组 */
  private void getDeptKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setContentField("extParam2");
    params.setTitle("选择部门");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_DEPT_TREE);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_CJDEPT);
  }
}
